import localforage from 'localforage'
import pako from 'pako'

// 配置本地存储
localforage.config({
  name: 'hubei-map-tiles',
  storeName: 'map_tiles'
})

export async function loadOfflineTiles() {
  try {
    // 检查是否已存储瓦片数据
    const cached = await localforage.getItem('tiles_cached')
    if (!cached) {
      // 加载预打包的瓦片数据
      const response = await fetch('/assets/map-data/tiles.dat')
      const compressed = await response.arrayBuffer()
      const tilesData = pako.inflate(new Uint8Array(compressed))
      
      // 存储到IndexedDB
      await Promise.all(
        Object.entries(JSON.parse(new TextDecoder().decode(tilesData))).map(
          ([key, value]) => localforage.setItem(key, value)
        )
      )
      await localforage.setItem('tiles_cached', true)
    }
  } catch (error) {
    console.error('离线瓦片加载失败:', error)
  }
}